﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using T.ServiceComponent.I18N.Service;
using T.FAS.Runtime.Base.Common;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.Page.Dao;
using T.FAS.Runtime.Metadata.Entity.Page;
//using T.SFP.Term.ClientService;
//using T.TTP.TFF.Entity;
using T.ServiceComponent.Cluster.Client;
using T.ServiceComponent.Kernel.Service;
using  T.ServiceFramework.ServiceGateway.Client;

namespace T.FAS.Runtime.Page.Dao
{
    public static class Tools
    {
        /* Todo
        /// <summary>
        /// 初始化功能映射表
        /// </summary>
        /// <param name="pageMetaData"></param>
        /// <param name="funcID"></param>
        /// <returns></returns>
        public static TFFFunctionMapping GetTFFFunctionMapping(PageMetaData pageMetaData,string funcID)
        {
            TFFFunctionMapping functionMapping = new TFFFunctionMapping();
            functionMapping.ID = Guid.NewGuid().ToString();
            functionMapping.PageID = pageMetaData.ID;
            functionMapping.PageName = pageMetaData.Name;
            functionMapping.PageNameTerm = $"Schema.Page.{pageMetaData.Code.Replace("_","")}.Name";
            functionMapping.FuncID = funcID;
            functionMapping.PCRouter = pageMetaData.Code;
            functionMapping.MobileRouter = pageMetaData.Code;
            functionMapping.CreateTime = DateTime.Now;
            functionMapping.LastModifyTime = DateTime.Now;
            return functionMapping;
        }
        */
        /// <summary>
        /// 初始化菜单实体
        /// </summary>
        /// <returns></returns>
        private static MenuEntity InitMenuEntity()
        {
            MenuEntity menuEntity = new MenuEntity();
            menuEntity.OldMenuID = "";
            menuEntity.IMG = "";
            menuEntity.Description = "";
            menuEntity.MenuType = "4";
            menuEntity.AppType = "6";
            menuEntity.IsShow = "1";
            menuEntity.Importance = "3"; //3 代表重要。
            menuEntity.IsAuthorityLimited = "1";
            menuEntity.AllowDelete = 0; //不允许删除
            menuEntity.DeleteMark = 0;
            menuEntity.IsData = 1; //允许数据权限
            menuEntity.Layer = 3;
            menuEntity.LayerCode = "";
            menuEntity.IsReferenced = "0";  //表示这个菜单是否是引用的其它菜单的标记，一般是第三方系统的菜单
            menuEntity.FormName = "";
            menuEntity.Path = "";
            menuEntity.AllowEdit = 0;

            menuEntity.PublishTime = DateTime.Now;
            menuEntity.Tester = "";
            menuEntity.DepartmentName = "";
            menuEntity.ModifyDate = DateTime.Now;

            return menuEntity;
        }
        /// <summary>
        /// 将界面元数据转换为菜单实体
        /// </summary>
        /// <param name="pageMetaData"></param>
        /// <returns></returns>
        public static MenuEntity ConvertToMenuEntity(PageMetaData pageMetaData)
        {
            MenuEntity menuEntity = InitMenuEntity();
            menuEntity.FullName = pageMetaData.Name;
            menuEntity.MenuID = pageMetaData.ID;
            menuEntity.ParentID = pageMetaData.Header.ModuleID;
            menuEntity.GroupID = pageMetaData.Header.GroupID;
            menuEntity.Code = pageMetaData.Code;
            menuEntity.NavigateUrl = "/" + pageMetaData.Code;
            menuEntity.Enabled = 1;
            menuEntity.ApplicationID = pageMetaData.Header.ApplicationID;
            menuEntity.SortCode = 1;
            menuEntity.IsShow = "0";
            menuEntity.TestCompletionTime = pageMetaData.LastModifyTime;
            menuEntity.Department = pageMetaData.Header.DepartmentID;
            menuEntity.DepartmentName = "";
            menuEntity.Manager = pageMetaData.Creator;
            menuEntity.ManagerName = pageMetaData.Creator;
            menuEntity.CreateUserID = pageMetaData.Creator;
            menuEntity.CreateUserName = pageMetaData.Creator;
            menuEntity.CreateDate = pageMetaData.CreateTime;
            menuEntity.ModifyUserID = pageMetaData.LastModifier;
            menuEntity.ModifyUserName = pageMetaData.LastModifier;
            menuEntity.ModifyDate = DateTime.Now;

            return menuEntity;
        }
        /// <summary>
        /// 将菜单元数据转换为菜单实体
        /// </summary>
        /// <param name="fasMenu"></param>
        /// <returns></returns>
        public static MenuEntity ConvertToMenuEntity(FasMenu fasMenu)
        {
            MenuEntity menuEntity = InitMenuEntity();
            List<Language> languages = LanguageService.GetSupportLanguages();
            if (languages != null && languages.Count > 0)
            {
                foreach (var lan in languages)
                {
                    if (lan.IsMainLanguage)
                    {
                        menuEntity.FullName = GetFullName(fasMenu, lan);
                    }
                    else if (lan.RepositoryCode.Contains("Lang1"))
                    {
                        menuEntity.FullName_Lang1 = GetFullName(fasMenu, lan);
                    }
                    else if (lan.RepositoryCode.Contains("Lang2"))
                    {
                        menuEntity.FullName_Lang2 = GetFullName(fasMenu, lan);
                    }
                    else if (lan.RepositoryCode.Contains("Lang3"))
                    {
                        menuEntity.FullName_Lang3 = GetFullName(fasMenu, lan);
                    }
                }
            }
            else
            {
                menuEntity.FullName = fasMenu.Name;
            }
            menuEntity.MenuID = fasMenu.ID;
            menuEntity.ParentID = fasMenu.ModuleID;
            menuEntity.GroupID = fasMenu.ParentID;
            menuEntity.Code = fasMenu.Code;
            menuEntity.NavigateUrl = fasMenu.Url;
            menuEntity.Enabled = fasMenu.Disabled ? 0 : 1;
            menuEntity.ApplicationID = fasMenu.ApplicationID;
            menuEntity.SortCode = fasMenu.SortCode;
            menuEntity.Reason = fasMenu.Disabled ? "低代码设计时禁用" : "";
            menuEntity.TestCompletionTime = fasMenu.LastModifyTime;
            menuEntity.Department = fasMenu.DepartmentID;
            menuEntity.Manager = fasMenu.Creator;
            menuEntity.ManagerName = fasMenu.CreatorUserName;
            menuEntity.CreateUserID = fasMenu.Creator;
            menuEntity.CreateUserName = fasMenu.CreatorUserName;
            menuEntity.CreateDate = fasMenu.CreateTime;
            menuEntity.ModifyUserID = fasMenu.LastModifier;
            menuEntity.ModifyUserName = fasMenu.LastModifierUserName;
            menuEntity.ModifyDate = DateTime.Now;
            menuEntity.IMG = fasMenu.MenuImage;

            return menuEntity;
        }
        /// <summary>
        /// 获取语言名称
        /// </summary>
        /// <param name="fasMenu"></param>
        /// <param name="lan"></param>
        /// <returns></returns>
        private static string GetFullName(FasMenu fasMenu, Language lan)
        {
            string name = fasMenu.Name;
            if (lan.DisplayCode == "zh-CN")
            {
                name = fasMenu.Name;
            }
            else if (fasMenu.TranslatedTerms.ContainsKey(lan.DisplayCode))
            {
                var item = fasMenu.TranslatedTerms[lan.DisplayCode].FirstOrDefault(t => t["Code"] == $"Schema.Menu.{fasMenu.MetaDataCode}.Name");
                if (item != null)
                {
                    name = item["TranslateText"];
                }
            }
            else
            {
                /* Todo
                name = TermClientService.GetInstance().GetTranslateText($"Schema.Menu.{fasMenu.MetaDataCode}.Name", lan.DisplayCode);
                if (string.IsNullOrEmpty(name))
                {
                    name = fasMenu.Name;
                }*/
            }
            return name;
        }
        /// <summary>
        /// 同步功能
        /// </summary>
        /// <param name="bizPermissionObject"></param>
        public static void SyncMenuEntity(PageMetaData pageMetaData)
        {
            try
            {
                MenuEntity menu = ConvertToMenuEntity(pageMetaData);

                var data = new Dictionary<string, string>();
                data["entity"] = JsonConvert.SerializeObject(menu);

                SyncData("SYSMgr_IMenuService_AddOrUpdateMenu", data);
            }
            catch (Exception ex)
            {
                throw new FasException(FasMenuExceptionCode.ImportToSysMenuFailed, $"界面元数据导出为系统菜单出错。", ex);
            }
        }
        /// <summary>
        /// 同步菜单
        /// </summary>
        /// <param name="bizPermissionObject"></param>
        public static void SyncMenuEntity(FasMenu fasMenu)
        {
            try
            {
                MenuEntity menu = ConvertToMenuEntity(fasMenu);

                var data = new Dictionary<string, string>();
                data["entity"] = JsonConvert.SerializeObject(menu);

                SyncData("SYSMgr_IMenuService_AddOrUpdateMenu", data);
            }
            catch (Exception ex)
            {
                throw new FasException(FasMenuExceptionCode.ImportToSysMenuFailed, $"FasMenu元数据导出为系统菜单出错。", ex);
            }
        }
        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="menuId"></param>
        /// <exception cref="FasException"></exception>
        public static void DeleteMenuEntity(string menuId)
        {
            try
            {
                var param = new Dictionary<string, string>();
                param["MenuID"] = menuId;
                param["Reason"] = "低代码平台元数据同步删除";
                param["ModifyUserName"] = "Fas";
                param["ModifyDate"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                var data = new Dictionary<string, string>();
                data["param"] = JsonConvert.SerializeObject(param);

                SyncData("SYSMgr_IMenuService_DeleteMenu", data);
            }
            catch (Exception ex)
            {
                throw new FasException(FasMenuExceptionCode.ImportToSysMenuFailed, $"FasMenu元数据删除菜单出错。", ex);
            }
        }

        public static void SyncData(string sgId, Dictionary<string, string> data)
        {
            string currentDataCenterId = AppClusterLocalClient.GetInstance().GetCurrentDataCenterId();

            var client = new SGHttpClient(true);
            var response = client.Post(currentDataCenterId, sgId, data, timeoutSeconds: 60);
            if (response.state == "0")
            {
                string content = string.Empty;
                foreach (var item in data.Values)
                {
                    content += item + "\r\n";
                }
                LogUtil.Log($"SG[{sgId}]调用出错,data:{content}\r\nSG返回结果：{response.errmsg}\r\n","Menu");

                throw new FasException(FasMenuExceptionCode.ImportToSysMenuFailed, $"SG[{sgId}]调用出错：" + response.errmsg);
            }
        }
    }
}
